package com.ruoyi.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.lang.tree.parser.NodeParser;
import com.ruoyi.common.utils.reflect.ReflectUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * 扩展 hutool TreeUtil 封装系统树构建
 *
 * @author Lion Li
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TreeBuildUtils extends TreeUtil {

    /**
     * 根据前端定制差异化字段
     */
    public static final TreeNodeConfig DEFAULT_CONFIG = TreeNodeConfig.DEFAULT_CONFIG.setNameKey("label");

    public static <T, K> List<Tree<K>> build(List<T> list, NodeParser<T, K> nodeParser) {
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        K k = ReflectUtils.invokeGetter(list.get(0), "parentId");
        return TreeUtil.build(list, k, DEFAULT_CONFIG, nodeParser);
    }


    /**
     * 获取指定节点的所有的子节点平铺
     *
     * @param tree
     * @param key
     * @param <T>
     * @return
     */
    public static <T> List<T> getPosterity(List<Tree<T>> tree, T key) {
        List<T> list = new ArrayList<>();
        for (Tree<T> tTree : tree) {
            if (tTree.getId().equals(key)) {
                list.add(tTree.getId());
                if (tTree.hasChild()) {
                    for (Tree<T> child : tTree.getChildren()) {
                        list.addAll(getPosterity(tTree.getChildren(), child.getId()));
                    }
                }
            }
        }
        return list;
    }

    /**
     * 获取指定节点的所有的叶子节点
     *
     * @param tree
     * @param <T>
     * @return
     */
    public static <T> List<T> getLeafsNodes(List<Tree<T>> tree) {
        List<T> list = new ArrayList<>();
        for (Tree<T> tTree : tree) {
            if (tTree.hasChild()) {
                List<Tree<T>> children = tTree.getChildren();
                list.addAll(getLeafsNodes(children));
            } else {
                list.add(tTree.getId());
            }
        }
        return list;
    }

}
